<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/5/22
 * Time: 14:47
 */

namespace App\Http\Controllers\PayInfo;

use App\Http\Controllers\PayInfo\WechatPayController;
use App\Models\OnlineRegistration;
use App\Models\OnlineRegistrationOrder;
use App\Models\OnlineRegistrationOrderPay;
use App\Models\OnlineRegistrationOrderRefund;
use App\Models\UserWechatInfo;
use App\Validate\OnlineRegistrationPayInfoValidate;
use Illuminate\Support\Facades\DB;

/**
 * 在线办证支付模块
 * Class PayInfo
 * @package app\port\controller
 */
class OnlineRegistrationPayInfoController extends CommonController
{
    private $validate = null;
    private $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->validate = new OnlineRegistrationPayInfoValidate();
        $this->model = new OnlineRegistrationOrder();
    }

    /**
     * 统一下单，获取支付所需的参数 (在线办证))
     * @param order_id  订单id
     */
    public function getPayInfo()
    {
        return $this->returnApi(202, '演示项目不支持在线支付！');

        // 自动验证
        if (!$this->validate->scene('get_pay_param')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $order_id = $this->request->order_id;
        $wechat_id = $this->request->user_info['wechat_id'];

        //直接修改状态
        $order_info = $this->model->find($order_id);

        if (empty($order_info)) {
            return $this->returnApi(203, '网络错误');
        }
        if ($order_info['is_pay'] != 1) {
            return $this->returnApi(203, '网络错误');
        }

        $wechat_id = request()->user_wechat_info['wechat_id'];
        $open_id = UserWechatInfo::where('id', $wechat_id)->value('open_id');
        $price = $order_info->price * 100; //支付金额转换为分
        $wechatPayObj = new WechatPayController($order_info->order_number, '在线办证押金', $price, $open_id, 'online_registration');
        $res = $wechatPayObj->pay();

        //  return $this->returnApi(202 , json_encode($res));

        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '获取失败');
    }


    /**
     * 支付成功,验证订单状态，验证成功后修改订单状态
     * @param order_id  订单id
     */
    public function paymentSuccess()
    {
        // 自动验证
        if (!$this->validate->scene('payment_success')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //直接修改状态
        $order_id = $this->request->order_id;
        $order_info = $this->model->find($order_id);
        if (empty($order_info)) {
            return $this->returnApi(203, '网络错误');
        }
        $onlineRegistrationModel = new OnlineRegistration();
        if ($order_info['is_pay'] == 1) {
            //自助验证状态
            $result = $this->checkWeChatPay($order_id);
            if ($result !== true) {
                $result = $result ? $result : '网络错误';
                return $this->returnApi(202, $result);
            }

            //写入文华系统
            $insertState = $this->insterRealData($order_id);
            if($insertState === true){
                $reader_id = OnlineRegistration::where('order_id' , $order_id)->value('reader_id');//只能分开重查，因为之前的没有这个数据

                $msg = '读者证办理成功！读者证号为【'.$reader_id.'】，初始密码为身份证号码中间8位生日，是否立即绑定？(建议您关注“渝中区图书馆”微信公众号，可收到图书借还、到期等提醒，避免图书超期。)';
                return $this->returnApi(200, $msg, true);
            }
            return $this->returnApi(202, $insertState);
        } elseif ($order_info['is_pay'] == 2) {
            $node = $onlineRegistrationModel->where('order_id' , $order_id)->value('node');
            if($node == 2){
                //写入文华系统
                $insertState = $this->insterRealData($order_id);
                if($insertState === true){
                    $reader_id = $onlineRegistrationModel->where('order_id' , $order_id)->value('reader_id');//只能分开重查，因为之前的没有这个数据

                    $msg = '读者证办理成功！读者证号为【'.$reader_id.'】，初始密码为身份证号码中间8位生日，是否立即绑定？(建议您关注“渝中区图书馆”微信公众号，可收到图书借还、到期等提醒，避免图书超期。)';
                    return $this->returnApi(200, $msg, true);
                }
                return $this->returnApi(202, $insertState);
            }else{
                $reader_id = $onlineRegistrationModel->where('order_id' , $order_id)->value('reader_id');//只能分开重查，因为之前的没有这个数据

                $msg = '读者证办理成功！读者证号为【'.$reader_id.'】，初始密码为身份证号码中间8位生日，是否立即绑定？(建议您关注“渝中区图书馆”微信公众号，可收到图书借还、到期等提醒，避免图书超期。)';
                return $this->returnApi(200, $msg, true);
            }
        }

        return $this->returnApi(202, '支付失败');
    }
    /**
     * 写入文华系统
     */
    public function insterRealData($order_id)
    {
        DB::beginTransaction();
        try {
            //获取读者证号
            $onlineRegistrationModel = new OnlineRegistration();
            $data = $onlineRegistrationModel->where('order_id', $order_id)->first();

            $reader_id = $onlineRegistrationModel->getReaderId($data['card_type']);
            if (empty($reader_id)) {
                throw  new \Exception('获取读者证号失败');
            }
            $onlineRegistrationModel->where('order_id', $order_id)->update(array(
                'reader_id' => $reader_id,
            ));

            //写入真实系统
            $libApi = $this->getLibApiObj();
            $data['reader_id'] = $reader_id;//读者证号
            $card_status = $libApi->readerIdAdd($data);
            if ($card_status['code'] !== 200) {
                $msg = mb_substr($card_status['msg'], 0, 36);
                if ($msg == $onlineRegistrationModel->contrastMsg) {
                    $card_status['msg'] = $onlineRegistrationModel->repetitionCertificateMsg;;
                }
                throw  new \Exception($card_status['msg']);
            } else {
                //修改本地状态为成功
                $onlineRegistrationModel->where('order_id', $order_id)->update(['node' => 1]);
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();

            //执行退款操作
            $this->refund($order_id);

            return $e->getMessage();
        }
    }

    /**
     * 推送
     */
    public function pushMsg($order_info)
    {
        //添加系统消息
        $system_id = $this->systemAdd('在线办证押金缴纳支付成功', $order_info['user_id'], $order_info['account_id'],25, $order_info['id'], '在线办证押金缴纳【' . $order_info['price'] . '元】成功');
    }

    /**
     * 查询微信支付系统
     */
    public function checkWeChatPay($order_id)
    {
        $order_info = $this->model->find($order_id);
        if ($order_info->is_pay == 2) {
            return true; //已支付成功
        }

        //调用微信查询接口
        $wechatPayObj = new WechatPayController($order_info->order_number);
        $result = $wechatPayObj->checkWxOrderPay();

        if (!$result) {
            return false;
            //return $this->returnData(203 , '数据异常');//实际为未查询到支付交易情况
        }
        //否则提交信息，修改数据
        //返回的$result为数组

        //微信支付订单号
        $trade_no = $result['transaction_id'];
        //订单支付时间
        $time_end = $result['time_end'];
        //转换为时间戳
        $gtime = strtotime($time_end);
        $gmt_payment = date("Y-m-d H:i:s", $gtime); //转换为日期时间格式
        //买家微信支付分配的终端设备号，
        //   $buyer_id  = $result['device_info'];
        //买家微信账号
        //	$buyer_login_id  = $_POST['buyer_login_id'];
        //订单总金额,订单总金额，单位为分
        $total_amount = $result['total_fee'];
        //实收金额,商家在交易中实际收到的款项
        $receipt_amount = $result['total_fee']; //微信的实收与总金额一致
        //付款金额,现金支付金额订单现金支付金额，详见支付金额
        $buyer_pay_amount = $result['cash_fee'];

        //此处编写回调处理逻辑
        $where = array(
            'order_number' => $order_info->order_number,
            'pay_time' => $gmt_payment,
            'payment' => 1,
            'trade_no' => $trade_no,
            //    'buyer_id'		=> $buyer_id,
            //	'buyer_login_id'=>$buyer_login_id,
            'total_amount' => $total_amount,
            'receipt_amount' => $receipt_amount,
            'buyer_pay_amount' => $buyer_pay_amount,
        );

        //开启事务
       DB::beginTransaction();
        try {
           $this->model->where('id', $order_id)->update(array('is_pay' => 2, 'change_time' => $gmt_payment));
           $onlineRegistrationOrderPay = new OnlineRegistrationOrderPay();
           $onlineRegistrationOrderPay->add($where);

            //获取读者证号
            $this->model->where('order_id', $order_id)->update(array(
                'is_pay' => 2,
                'change_time' => $gmt_payment,
            ));
            //添加推送信息
            $this->pushMsg($order_info);

            DB::commit();
            return true;    //支付成功
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }


    /**
     * 写入文华接口失败，办证失败，进行退款操作
     * @param order_id 订单id
     * @param refund_remark 退款备注
     */
    public function refund($order_id, $refund_remark = '办证失败')
    {
        $online_registration_info = $this->model->where('order_id', $order_id)->first();
        $order_info = $this->model->find($order_id);
        if (empty($order_info)) {
            return $this->returnApi(202, '订单获取失败');
        }
        if (empty($online_registration_info)) {
            return $this->returnApi(202, '获取办证信息失败');
        }
        if ($order_info['is_pay'] == 5) {
            return $this->returnApi(202, '此订单已退款，无需重复操作');
        }
        if ($order_info['is_pay'] != 2) {
            return $this->returnApi(202, '订单异常');
        }

        $refund_no = get_order_id();
        $trade_no = OnlineRegistrationOrderPay::where('order_number', $order_info->order_number)->value('trade_no');  //微信支付订单号
        $wxReturnMoney = new WxReturnMoneyController();

        $return_info = $wxReturnMoney->doRefund($order_info->dis_price, $order_info->dis_price, $refund_no, $trade_no, $order_info->order_number, $refund_remark);

        $onlineRegistrationOrderRefundModel = new OnlineRegistrationOrderRefund();
        $time = date('Y-m-d H:i:s');
        if ($return_info['code'] === 200) {
            //退款成功
            DB::beginTransaction();
            try {
                $onlineRegistrationOrderRefundModel->refund_number = $refund_no;
                $onlineRegistrationOrderRefundModel->refund_id = $return_info['refund_id'];
                $onlineRegistrationOrderRefundModel->refund_time = $time;
                $onlineRegistrationOrderRefundModel->price = $order_info->price;
                $onlineRegistrationOrderRefundModel->payment = 1;
                $onlineRegistrationOrderRefundModel->status = 1;
                $onlineRegistrationOrderRefundModel->manage_id = null;//表示自己退款
                $onlineRegistrationOrderRefundModel->save();
                //修改订单状态
                $order_info->is_pay = 5;
                $order_info->refund_number = $refund_no;
                $order_info->refund_time = $time;
                $order_info->refund_remark = $refund_remark;
                $order_info->refund_manage_id = null;//表示自己退款
                $order_info->save();

                //修改在线办证表
                OnlineRegistration::where('order_id', $order_info['id'])->update(['is_pay' => 5]);

                //添加系统消息
                $this->systemAdd('在线办证：押金已成功退回', $order_info->user_id,$order_info->account_id, 26, $order_id, '押金已成功退回；退回理由: ' . $refund_remark);

                DB::commit();
                return $this->returnApi(200, '退款成功');
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->returnApi(202, '退款失败');
            }
        } else {
            //添加退款日志
            $onlineRegistrationOrderRefundModel->refund_number = $refund_no;
            $onlineRegistrationOrderRefundModel->refund_time = $time;
            $onlineRegistrationOrderRefundModel->price = $order_info->price;
            $onlineRegistrationOrderRefundModel->payment = 1;
            $onlineRegistrationOrderRefundModel->status = 2;
            $onlineRegistrationOrderRefundModel->manage_id = null;
            if (isset($return_info['err_code'])) $onlineRegistrationOrderRefundModel->error_code = $return_info['err_code'];

            $onlineRegistrationOrderRefundModel->error_msg = $return_info['msg'];
            $onlineRegistrationOrderRefundModel->save();

            //退款失败
            return $this->returnApi(202, $return_info['msg']);
        }
    }
}
